import os
import shutil


def merge_txt_files(path_A, path_B, path_C):
    os.makedirs(path_C, exist_ok=True)

    files_A = set(os.listdir(path_A))
    files_B = set(os.listdir(path_B))

    all_files = files_A | files_B  # 获取所有唯一文件名

    for file in all_files:
        file_A = os.path.join(path_A, file)
        file_B = os.path.join(path_B, file)
        file_C = os.path.join(path_C, file)

        if file in files_A and file in files_B and file.endswith('.txt'):
            # 两个路径下都有同名 .txt 文件，进行合并
            with open(file_C, 'w', encoding='utf-8') as f_out:
                for src in [file_A, file_B]:
                    with open(src, 'r', encoding='utf-8') as f_in:
                        lines = [line.strip() for line in f_in if line.strip()]
                        f_out.write('\n'.join(lines) + '\n')
        else:
            # 仅存在于一个路径，直接复制到 C
            src = file_A if file in files_A else file_B
            shutil.copy(src, file_C)


if __name__ == "__main__":
    path_A = r"E:\2025-03-20_17_16_09_auto_annotate_labels"  # 修改为实际路径
    path_B = r"E:\2025-03-20_17_16_09_white_auto_annotate_labels"  # 修改为实际路径
    path_C = r"E:\2025-03-20_17_16_09_merge"  # 修改为实际路径
    merge_txt_files(path_A, path_B, path_C)
